package gaoji;

/**
 * 标志法
 */
public class TestNotify2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}
class Player extends Thread{
    TV tv;
    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                this.tv.play("节目");
            } else {
                this.tv.play("广告时间");
            }
        }
    }
}
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            tv.watch();
        }
    }
}

class TV{
    String video;//节目
    boolean flag = true;//T 录制 F 录制完成

    public synchronized void play(String video){
        if (!flag) {//录制未完成
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //录制完成
        this.flag = !this.flag;
        this.video = video;
        System.out.println("表演:" + video);
        this.notifyAll();
    }
    public synchronized void watch(){
        if (flag) {//录制未完成
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //录制完成
        this.flag = !this.flag;
        System.out.println("观看:"+video);
        this.notifyAll();
    }
}
